package com.lizonghui.googleplay.fragment;

import android.os.SystemClock;
import android.view.View;
import android.widget.AbsListView;
import android.widget.ListView;

import com.lizonghui.googleplay.adapter.ItemAdapter;
import com.lizonghui.googleplay.base.BaseFragment;
import com.lizonghui.googleplay.base.LoadingPager;
import com.lizonghui.googleplay.bean.DownLoadInfo;
import com.lizonghui.googleplay.bean.HomeInfoBean;
import com.lizonghui.googleplay.bean.ItemInfoBean;
import com.lizonghui.googleplay.control.HomePictureHolder;
import com.lizonghui.googleplay.control.ItemHolder;
import com.lizonghui.googleplay.factory.ListViewFactory;
import com.lizonghui.googleplay.manager.DownLoadManger;
import com.lizonghui.googleplay.protocol.HomeProtocol;

import java.io.IOException;
import java.util.List;

/**
 * Created by Administrator on 2016/6/16.
 */
public class HomeFragment extends BaseFragment {

    private List<ItemInfoBean> mItemInfoBeans;
    private List<String> mPictures;
    private HomeProtocol mHomeProtocol;
    private MyHomeAdapter mAdapter;


    @Override
    public LoadingPager.LoadedResultState initData() {
     /*   try {
            //使用okHttp请求网络数据
            //创建okHttpClient实例对象
            OkHttpClient okHttpClient = new OkHttpClient();

            String url = Constants.URLS.BASEURL + "home?";
            //参数
            Map<String, Object> parmasMap = new HashMap<>();
            parmasMap.put("index", "" + 0);
            String urlParamsByMap = HttpUtils.getUrlParamsByMap(parmasMap);
            //dir=E:\\GooglePlay\\googlePlay_day01\\资料\\服务器
            //http://localhost:8080/GooglePlayServer/home?index=0这里不能是localhost，要是具体IP
            //http://192.168.0.83:8080/GooglePlayServer/home?index=1
            //拼接之后的结果
            url = url + urlParamsByMap;

            //创建一个请求对象
            Request request = new Request.Builder().get().url(url).build();

            //发起同步请求,因为这里已经是子线程，所以用同步请求
            Response response = okHttpClient.newCall(request).execute();

            if (response.isSuccessful()) {//响应成功
                String resultJsonString = response.body().string();

                //解析用Gson
                Gson gson = new Gson();
                HomeInfoBean homeInfoBean = gson.fromJson(resultJsonString, HomeInfoBean.class);
                //每次返回都要判断返回的JSON值，这里我们定义方法在BaseFragment

               //校验homeInfoBean
                LoadingPager.LoadedResultState state = checkResData(homeInfoBean);
                if (state != LoadingPager.LoadedResultState.SUCCESS) {
                    //不成功-->说明homeInfoBean为空
                    return state;
                }
                //校验homeInfoBean.list
              state = checkResData(homeInfoBean.list);
                if(state != LoadingPager.LoadedResultState.SUCCESS){
                    //不成功，说明homeInfoBean.list.size()==0
                    return state;
                }

                //走到这里的话，一切数据都顺利！！
                //就开始保存数据了
                mItemInfoBeans = homeInfoBean.list;
                mPictures = homeInfoBean.picture;


                return state;
            }else {
                return LoadingPager.LoadedResultState.ERROR;
            }

        } catch (IOException e) {
            e.printStackTrace();
            return LoadingPager.LoadedResultState.ERROR;
        }*/
        /*--------------请求加载协议简单封装之后,把代码移动到别的地方而已------------------*/
        mHomeProtocol = new HomeProtocol();
        try {
            HomeInfoBean homeInfoBean = mHomeProtocol.loadData(0);


            //校验homeInfoBean
            LoadingPager.LoadedResultState state = checkResData(homeInfoBean);
            if (state != LoadingPager.LoadedResultState.SUCCESS) {
                //不成功-->说明homeInfoBean为空
                return state;
            }
            //校验homeInfoBean.list
            state = checkResData(homeInfoBean.list);
            if (state != LoadingPager.LoadedResultState.SUCCESS) {
                //不成功，说明homeInfoBean.list.size()==0
                return state;
            }

            //走到这里的话，一切数据都顺利！！
            //就开始保存数据了
            mItemInfoBeans = homeInfoBean.list;
            mPictures = homeInfoBean.picture;
            return state;
        } catch (IOException e) {
            e.printStackTrace();
            return LoadingPager.LoadedResultState.ERROR;
        }

    }

    @Override
    public View initSuccessView() {
        ListView mListView = ListViewFactory.createListView();

        //设置adapter之前，添加一个轮播图。holder就是data+view
        HomePictureHolder homePictureHolder = new HomePictureHolder();
        //添加一个经过数据绑定过的一个view。HeaderView要在setAdapter之前
        mListView.addHeaderView(homePictureHolder.mHolderView);
        //传递数据给HomePicture让其刷新
        homePictureHolder.setDataAndRefreshHolderView(mPictures);
        mAdapter = new MyHomeAdapter(mListView, mItemInfoBeans);
        mListView.setAdapter(mAdapter);//这里看清楚是把哪一项数据加载进去
        return mListView;

    }

    //我们的超级适配器是泛型，需要告诉适配的数据类型
    class MyHomeAdapter extends ItemAdapter {
        public MyHomeAdapter(AbsListView absListView, List datas) {
            super(absListView, datas);
        }

        /**
         * @return
         * @des 开始在子线程加载更多数据
         * @call listView滑到底时候调用，当没有加载更多时候就用不到这个方法
         */
        @Override
        public List<ItemInfoBean> initLoadMoreData() throws Exception {
            SystemClock.sleep(3000);
            /*------------*/
            HomeInfoBean homeInfoBean = mHomeProtocol.loadData(mItemInfoBeans.size());
            if (homeInfoBean != null) {
                return homeInfoBean.list;
            }
            return null;
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        //移除所有观察者,观察者在holder中建立，并通过adapter返回给ListView.所以用adapter作为判断位
        if(mAdapter != null){
            List<ItemHolder> itemHolders = mAdapter.itemHolders;
            for (ItemHolder itemHolder:itemHolders) {
                DownLoadManger.getInstance().deleteObserver(itemHolder);
            }
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        //添加所有观察者
        if(mAdapter != null){
            List<ItemHolder> itemHolders = mAdapter.itemHolders;
            for (ItemHolder itemHolder:itemHolders) {
                DownLoadManger.getInstance().addObserver(itemHolder);


                 //根据itemHolder的数据，得到downLoadInfo
                DownLoadInfo downLoadInfo = DownLoadManger.getInstance().getDownLoadInfo(itemHolder.mInfoBean);
                //手动发布最新消息，让UI刷新
                DownLoadManger.getInstance().notifyObservers(downLoadInfo);//要拿到downLoadInfo,而我们有
            }
        }
    }
}
